#!/usr/local/bin/python

import argparse
import os
import sys
import psycopg2
import subprocess


parser = argparse.ArgumentParser(description= """

DESCRIPTION:

    Uploads to postgres table file_stats the file produced by get_file_stats2.py.
    Only rows not identical to those already present in file_stats are inserted.
    
EXAMPLES:

    ## These produce a string formatted as dictionary
    get_file_stats2.py myfile1.txt >> fstats.txt
    get_file_stats2.py myfile2.txt >> fstats.txt
    
    ## Upload stats
    upload_file_stats.py -f fstats.txt
    
""", formatter_class= argparse.RawTextHelpFormatter)

parser.add_argument('--filestats', '-f',
                   required= True,
                   help='''A file of file stats. Each line is a python dictionary.
Typically procudeced by get_file_stats2.py 
                   ''')

args = parser.parse_args()

# --------------------------------[ Functions ]---------------------------------

def get_psycopgpass():
    """
    Read file ~/.psycopgpass to get the connection string to pass to
    psycopg2.connect()
    """
    conn= open(os.path.join(os.getenv("HOME"), '.psycopgpass'))
    conn= conn.readlines()
    conn_args= [x.strip() for x in conn if x.strip() != '' and x.strip().startswith('#') is False][0]
    return(conn_args)


# -----------------------[ Get file with stats ]--------------------------------

fstats= open(args.filestats).readlines()
fstats= (eval(x.strip()) for x in fstats)

# ---------------------------[ Upload to postgres ]-----------------------------
conn= psycopg2.connect(get_psycopgpass())
cur= conn.cursor()
cur.execute("CREATE TEMP TABLE fstats (LIKE file_stats)")
cur.executemany("INSERT INTO fstats VALUES (%(filename)s, %(path)s, %(hostname)s, %(fsize)s, %(mtime)s, %(ctime)s, %(md5sum)s)", fstats)
cur.execute('INSERT INTO file_stats (SELECT * FROM fstats EXCEPT SELECT * FROM file_stats)')
conn.commit()
cur.close()
conn.close()

sys.exit()
